GLSL sign function

GLSL
Author

Randall Rauwendaal

Published

February 10, 2011

The GLSL sign function always seems a great way to remove some unnecessary if statements from my shaders, but I never seem to get to use it because I always need to consider zero as either positive or negative, and not its own special value.

Anyway, I just realized you can accomplish the same thing with the step function.

step(0, x)*2 - 1;

This will return -1.0 if x < 0, and 1.0 if x >= 0.

Which is not terribly readable, hence this overly verbose function

// returns -1.0 if x < 0, and 1.0 if x >= 0
float signGreaterEqualZero(float x)
{
    return step(0, x)*2 - 1;
}

Citation

BibTeX citation:
@online{rauwendaal2011,
  author = {Randall Rauwendaal},
  title = {GLSL Sign Function},
  date = {2011-02-10},
  url = {https://raegnar.github.io/rauwendaal.net//posts/2012_06_15 - GLSL Sign Function},
  langid = {en}
}
For attribution, please cite this work as:
Randall Rauwendaal. 2011. “GLSL Sign Function.” February 10, 2011. https://raegnar.github.io/rauwendaal.net//posts/2012_06_15 - GLSL Sign Function.